package com.valuegroup.smarttodo.ui.programme.weekplan;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextPaint;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.common.BaseViewHolder;
import com.valuegroup.smarttodo.common.CommonRecyclerAdapter;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.vo.EventStatisticsVo;
import com.valuegroup.smarttodo.data.vo.WeekProgressVo;
import com.valuegroup.smarttodo.plugins.pickdialog.DatePickDialog;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.plugins.pickdialog.OnCustomSureLisener;
import com.valuegroup.smarttodo.plugins.pickdialog.bean.DateType;
import com.valuegroup.smarttodo.plugins.progressbar.VerticalProgress;
import com.valuegroup.smarttodo.plugins.progressbar.roundcorner.RoundCornerProgressBar;
import com.valuegroup.smarttodo.ui.programme.summarize.SumActivity;

import java.util.Date;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 规划 > 周计划聚合-首页
 */
public class WeekPlanFragment extends Fragment {

    @BindView(R.id.btnGoArrange)
    LinearLayout btnGoArrange;
    @BindView(R.id.btnSelectWeek)
    LinearLayout btnSelectWeek;
    @BindView(R.id.labSelectWeek)
    TextView labSelectWeek;
    @BindView(R.id.btnGoWeekPlan)
    LinearLayout btnGoWeekPlan;
    @BindView(R.id.btnGoSum)
    LinearLayout btnGoSum;
//    @BindView(R.id.btnGoWeekPlan)
//    LinearLayout btnGoWeekPlan;

    @BindView(R.id.recycler_week_progress_list)
    RecyclerView recyclerView;

    @BindView(R.id.labCurriculumEvent)
    TextView labCurriculumEvent;
    @BindView(R.id.labGoalEvent)
    TextView labGoalEvent;
    @BindView(R.id.labHabitEvent)
    TextView labHabitEvent;
    @BindView(R.id.labTotalEvent)
    TextView labTotalEvent;
    @BindView(R.id.labEventPoolBranch)
    TextView labEventPoolBranch;
    @BindView(R.id.labEventPoolPercent)
    TextView labEventPoolPercent;
    @BindView(R.id.progressPool)
    RoundCornerProgressBar progressPool;

    private WeekProgressAdapter adapter;
    private Unbinder unbinder;
    private int startPosition = 0;
    private String countFormat;
    private EventStatisticsVo eventStatistics;
    private boolean initFinish;
    private Integer selYearWeekNum;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_weekplan, container, false);
        unbinder = ButterKnife.bind(this, view);
        countFormat = getResources().getString(R.string.event_count);
        initFinish = true;
        selYearWeekNum = DateUtils.getYearWeekNumber(new Date());

        initView();
        initData();

        setHasOptionsMenu(true);
        return view;
    }

    private void initData() {
        loadEventStat();
    }

    private void loadEventStat() {
        // 读取指定周的事件统计数据
        eventStatistics = ServiceFactory.getInstance().getEventService().countAllEvent(selYearWeekNum);
        int year = Integer.parseInt(String.valueOf(selYearWeekNum).substring(0, 4));
        int week = Integer.parseInt(String.valueOf(selYearWeekNum).substring(4));
        labSelectWeek.setText(year + "年" + week + "周");

        // card1
        labCurriculumEvent.setText(String.format(countFormat, eventStatistics.getStudyFinish(), eventStatistics.getStudyTotal()));
        labGoalEvent.setText(String.format(countFormat, eventStatistics.getGoalFinish(), eventStatistics.getGoalTotal()));
        labHabitEvent.setText(String.format(countFormat, eventStatistics.getHabitFinish(), eventStatistics.getHabitTotal()));
        labTotalEvent.setText(String.format(countFormat, eventStatistics.getEventFinish(), eventStatistics.getEventTotal()));

        // card2 eventPool
        labEventPoolBranch.setText(String.format(getResources().getString(R.string.event_statistics), eventStatistics.getPoolSchedu(), eventStatistics.getPoolTotal()));
        labEventPoolPercent.setText(String.format(getResources().getString(R.string.percent_tag), Math.round(eventStatistics.getPoolPercent())));
        progressPool.setProgress(eventStatistics.getPoolPercent());
    }

    private void initView() {
        // 每日执行概况列表
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new WeekProgressAdapter(getContext(), loadWeekProgressData());
        recyclerView.setAdapter(adapter);

        // 平移到指定位置
        recyclerView.smoothScrollToPosition(startPosition);

        // 选择要统计的周
        btnSelectWeek.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DatePickDialog dialog = new DatePickDialog(view.getContext());
                dialog.setYearLimt(5);
                dialog.setType(DateType.TYPE_CUSTOM_YEAR_WEEK);
                dialog.setStartData(String.valueOf(selYearWeekNum));
                dialog.setOnCustomSureLisener(new OnCustomSureLisener() {
                    @Override
                    public void onSure(Object obj) {
                        selYearWeekNum = Integer.valueOf(obj.toString());
                        refreshAllData();
                    }
                });
                dialog.show();
            }
        });
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        //先clear()一下, 这样按钮就只有Fragment中设置的自己的了, 不会有Activity中的按钮.
        menu.clear();
        inflater.inflate(R.menu.menu_weekplan, menu);
    }

    private List<WeekProgressVo> loadWeekProgressData() {
        List<WeekProgressVo> data = ServiceFactory.getInstance().getEventService().countWeekProgressData(selYearWeekNum);
        startPosition = 0;
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).isShowToday()) {
                startPosition = i;
            }
        }
        return data;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        switch (item.getItemId()) {
            case R.id.menu_week_plan_1:
                startActivityForResult(new Intent(getContext(), WeekArrangeActivity.class), 1003);
                break;
            case R.id.menu_week_plan_2:
                startActivityForResult(new Intent(getContext(), WeekEventPoolActivity.class), 1003);
                break;
            case R.id.menu_week_plan_3:
                startActivityForResult(new Intent(getContext(), WeekTimelineActivity.class), 1003);
                break;
            /*case R.id.menu_week_plan_4:
                startActivityForResult(new Intent(getContext(), GoalsDetailActivity.class), 1003);
                break;*/
        }
        return true;
    }

    private void refreshAllData() {
        initData();
        // 刷新列表数据
        adapter.refreshListData(loadWeekProgressData());
        // 平移到相关位置
        recyclerView.smoothScrollToPosition(startPosition);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        refreshAllData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        /*if (isVisibleToUser && initFinish) {
            refreshAllData();
        }*/
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public static WeekPlanFragment newInstance() {
        return new WeekPlanFragment();
    }

    @OnClick({R.id.btnGoArrange, R.id.btnGoWeekPlan, R.id.layoutCount, R.id.btnGoSum})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.layoutCount:
                labCurriculumEvent.setText(String.format(countFormat, eventStatistics.getStudyFinish(), eventStatistics.getStudyTotal()));
                labGoalEvent.setText(String.format(countFormat, eventStatistics.getGoalFinish(), eventStatistics.getGoalTotal()));
                labHabitEvent.setText(String.format(countFormat, eventStatistics.getHabitFinish(), eventStatistics.getHabitTotal()));
                labTotalEvent.setText(String.format(countFormat, eventStatistics.getEventFinish(), eventStatistics.getEventTotal()));
                break;
            case R.id.btnGoArrange:
                // 事务安排
                startActivityForResult(new Intent(getContext(), WeekArrangeActivity.class), 1003);
                break;
            case R.id.btnGoWeekPlan:
                // 事务列表
                Intent intent = new Intent(getContext(), WeekTimelineActivity.class);
                //intent.putExtra(PARAMS_KEY, DATA.getId());
                //intent.putExtra(PARAMS_POSITION, DATA_POSITION);
                startActivityForResult(intent, 1001);
                break;
            case R.id.btnGoSum:
                // 总结
                startActivityForResult(new Intent(getContext(), SumActivity.class), 1003);
                break;
           /* case R.id.btnGoEventPool:
                // 事务池
                startActivityForResult(new Intent(getContext(), WeekEventPoolActivity.class), 1003);
                break;*/
        }
    }

    /**
     * 周计划进展统计图水平列表适配器
     */
    class WeekProgressAdapter extends CommonRecyclerAdapter<WeekProgressVo> {

        public WeekProgressAdapter(Context context, List<WeekProgressVo> data) {
            super(context, data);
            setMainLayoutId(R.layout.item_week_progress);
        }

        @Override
        public void bindHeadView(BaseViewHolder v, int position) {

        }

        @Override
        public void bindBottomView(BaseViewHolder v, int position) {

        }

        @Override
        public void bindMainView(BaseViewHolder v, int position) {

            WeekProgressVo data = getData(position);

            v.getView(R.id.layoutRoot).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    labCurriculumEvent.setText(String.format(countFormat, data.getStudyFinish().intValue(), data.getStudyTotal().intValue()));
                    labGoalEvent.setText(String.format(countFormat, data.getGoalFinish().intValue(), data.getGoalTotal().intValue()));
                    labHabitEvent.setText(String.format(countFormat, data.getHabitFinish().intValue(), data.getHabitTotal().intValue()));
                    labTotalEvent.setText(String.format(countFormat, data.getTotalFinish().intValue(), data.getTotal().intValue()));
                }
            });

            VerticalProgress pgsGoal = v.getView(R.id.pgsGoal);
            VerticalProgress pgsHabit = v.getView(R.id.pgsHabit);
            VerticalProgress pgsStudy = v.getView(R.id.pgsStudy);

            TextView labDate = v.getView(R.id.labDate);
            v.setText(R.id.labDate, data.getLabDate());
            if (data.isShowToday()) {
                // 当天
                labDate.setTextColor(ContextCompat.getColor(getmContext(), R.color.colorLink));
                // 加粗
                TextPaint tp = labDate.getPaint();
                tp.setFakeBoldText(true);
            } else {
                TextPaint tp = labDate.getPaint();
                tp.setFakeBoldText(false);
                if (data.isShowOut()) {
                    // 过去
                    labDate.setTextColor(ContextCompat.getColor(getmContext(), R.color.textHint));
                } else {
                    // 未来
                    labDate.setTextColor(ContextCompat.getColor(getmContext(), R.color.textDefault));
                }
            }
            pgsHabit.setProgress(0);
            pgsStudy.setProgress(0);
            pgsGoal.setProgress(0);
            if (data.getHabitTotal() > 0) {
                pgsHabit.setProgress(Math.round(data.getHabitFinish() / data.getHabitTotal() * 100));
            }
            if (data.getStudyTotal() > 0) {
                pgsStudy.setProgress(Math.round(data.getStudyFinish() / data.getStudyTotal() * 100));
            }
            if (data.getGoalTotal() > 0) {
                pgsGoal.setProgress(Math.round(data.getGoalFinish() / data.getGoalTotal() * 100));
            }
        }

        @Override
        public void bindAppendView(BaseViewHolder v, int position) {

        }
    }


}
